<template>
  <view class="cache-test-page">
    <view class="header">
      <text class="title">缓存管理测试</text>
      <text class="subtitle">测试组织切换时的缓存清除功能</text>
    </view>
    
    <view class="section">
      <text class="section-title">当前状态</text>
      <view class="info-card">
        <view class="info-item">
          <text class="label">当前用户ID:</text>
          <text class="value">{{ currentUserId }}</text>
        </view>
        <view class="info-item">
          <text class="label">当前组织ID:</text>
          <text class="value">{{ currentOrgId }}</text>
        </view>
        <view class="info-item">
          <text class="label">上次用户ID:</text>
          <text class="value">{{ lastUserId }}</text>
        </view>
        <view class="info-item">
          <text class="label">上次组织ID:</text>
          <text class="value">{{ lastOrgId }}</text>
        </view>
      </view>
    </view>
    
    <view class="section">
      <text class="section-title">缓存状态</text>
      <view class="cache-status">
        <view class="cache-item" v-for="(cache, key) in cacheStatus.caches" :key="key">
          <view class="cache-name">{{ key }}</view>
          <view class="cache-info">
            <text class="cache-exists" :class="{ active: cache.exists }">{{ cache.exists ? '存在' : '不存在' }}</text>
            <text class="cache-time" v-if="cache.timestamp">{{ cache.timestamp }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <view class="section">
      <text class="section-title">操作</text>
      <view class="button-group">
        <button class="btn primary" @click="checkOrgSwitch">检查组织切换</button>
        <button class="btn secondary" @click="clearCurrentOrgCache">清除当前组织缓存</button>
        <button class="btn danger" @click="clearAllCache">清除所有缓存</button>
        <button class="btn info" @click="refreshCacheStatus">刷新缓存状态</button>
      </view>
    </view>
    
    <view class="section">
      <text class="section-title">错误处理测试</text>
      <view class="button-group">
        <button class="btn" style="background: #faad14; color: white;" @click="testUserInfoError">测试用户信息异常错误</button>
        <button class="btn" style="background: #faad14; color: white;" @click="test401Error">测试401错误</button>
      </view>
    </view>
    
    <view class="section">
      <text class="section-title">日志</text>
      <scroll-view class="log-container" scroll-y>
        <view class="log-item" v-for="(log, index) in logs" :key="index">
          <text class="log-time">{{ log.time }}</text>
          <text class="log-message">{{ log.message }}</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import cacheManager from '@/utils/cacheManager.js'
import { API_CONFIG } from '@/api/config.js'
import { getUserInfo } from '@/utils/auth.js'

export default {
  data() {
    return {
      currentUserId: '',
      currentOrgId: '',
      lastUserId: '',
      lastOrgId: '',
      cacheStatus: {
        caches: {}
      },
      logs: []
    }
  },
  
  onLoad() {
    this.loadCurrentStatus()
    this.refreshCacheStatus()
    this.addLog('页面加载完成')
  },
  
  methods: {
    // 加载当前状态
    loadCurrentStatus() {
      try {
        const userInfo = getUserInfo()
        this.currentUserId = userInfo ? userInfo.userId : '未登录'
        this.currentOrgId = API_CONFIG.ORG_ID
        this.lastUserId = uni.getStorageSync('last_user_id') || '无记录'
        this.lastOrgId = uni.getStorageSync('last_org_id') || '无记录'
      } catch (error) {
        this.addLog(`加载状态失败: ${error.message}`)
      }
    },
    
    // 检查组织切换
    checkOrgSwitch() {
      try {
        this.addLog('开始检查组织切换...')
        
        // 模拟组织切换检测逻辑
        const orgChanged = this.lastOrgId && this.lastOrgId !== 'undefined' && this.lastOrgId !== this.currentOrgId
        const userChanged = this.lastUserId && this.lastUserId !== 'undefined' && this.lastUserId !== this.currentUserId
        
        if (orgChanged) {
          this.addLog(`检测到组织切换: ${this.lastOrgId} -> ${this.currentOrgId}`)
          cacheManager.clearOrgCache(this.lastOrgId)
          cacheManager.clearOrgCache(this.currentOrgId)
        } else if (userChanged) {
          this.addLog(`检测到用户切换: ${this.lastUserId} -> ${this.currentUserId}`)
          cacheManager.clearOrgCache(this.currentOrgId)
        } else {
          this.addLog('未检测到组织或用户切换')
        }
        
        // 更新记录
        uni.setStorageSync('last_user_id', this.currentUserId)
        uni.setStorageSync('last_org_id', this.currentOrgId)
        
        this.loadCurrentStatus()
        this.refreshCacheStatus()
        
      } catch (error) {
        this.addLog(`组织切换检查失败: ${error.message}`)
      }
    },
    
    // 清除当前组织缓存
    clearCurrentOrgCache() {
      try {
        this.addLog(`开始清除组织 ${this.currentOrgId} 的缓存...`)
        cacheManager.clearOrgCache(this.currentOrgId)
        this.addLog('当前组织缓存清除完成')
        this.refreshCacheStatus()
      } catch (error) {
        this.addLog(`清除缓存失败: ${error.message}`)
      }
    },
    
    // 清除所有缓存
    clearAllCache() {
      try {
        this.addLog('开始清除所有缓存...')
        cacheManager.clearAllCache()
        this.addLog('所有缓存清除完成')
        this.refreshCacheStatus()
      } catch (error) {
        this.addLog(`清除所有缓存失败: ${error.message}`)
      }
    },
    
    // 刷新缓存状态
    refreshCacheStatus() {
      try {
        this.cacheStatus = cacheManager.getCacheStatus(this.currentOrgId)
        this.addLog('缓存状态已刷新')
      } catch (error) {
        this.addLog(`刷新缓存状态失败: ${error.message}`)
      }
    },
    
    // 测试用户信息异常错误
    testUserInfoError() {
      this.addLog('测试用户信息异常错误...')
      const mockError = {
        response: {
          status: 500,
          data: {
            msg: '服务器错误: 获取订单统计失败：获取用户信息异常'
          }
        }
      }
      
      handleApiError(mockError, {
        showToast: true,
        autoRedirect: true,
        autoWechatLogin: true
      })
      
      this.addLog('用户信息异常错误测试完成 - 应该弹出登录确认窗口，点击重新登录会清除登录状态并跳转到登录页')
    },

    // 测试401错误
      test401Error() {
        this.addLog('测试401错误...')
        const mockError = {
          response: {
            status: 401,
            data: {
              msg: '未授权访问'
            }
          }
        }
        
        handleApiError(mockError, {
          showToast: true,
          autoRedirect: true,
          autoWechatLogin: true
        })
        
        this.addLog('401错误测试完成 - 应该弹出登录确认窗口，点击重新登录会清除登录状态并跳转到登录页')
      },
    
    // 添加日志
    addLog(message) {
      const now = new Date()
      const time = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`
      this.logs.unshift({
        time,
        message
      })
      
      // 限制日志数量
      if (this.logs.length > 50) {
        this.logs = this.logs.slice(0, 50)
      }
      
      console.log(`[缓存测试] ${time} ${message}`)
    }
  }
}
</script>

<style lang="scss" scoped>
.cache-test-page {
  padding: 20rpx;
  background: #f5f5f5;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 40rpx;
  
  .title {
    display: block;
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
  }
  
  .subtitle {
    display: block;
    font-size: 28rpx;
    color: #666;
  }
}

.section {
  margin-bottom: 40rpx;
  
  .section-title {
    display: block;
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
  }
}

.info-card {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  
  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .label {
      font-size: 28rpx;
      color: #666;
    }
    
    .value {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
    }
  }
}

.cache-status {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  
  .cache-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .cache-name {
      font-size: 28rpx;
      color: #333;
      text-transform: capitalize;
    }
    
    .cache-info {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      
      .cache-exists {
        font-size: 24rpx;
        padding: 4rpx 12rpx;
        border-radius: 12rpx;
        background: #f0f0f0;
        color: #999;
        
        &.active {
          background: #e8f5e8;
          color: #52c41a;
        }
      }
      
      .cache-time {
        font-size: 20rpx;
        color: #999;
        margin-top: 4rpx;
      }
    }
  }
}

.button-group {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  
  .btn {
    padding: 24rpx;
    border-radius: 12rpx;
    font-size: 28rpx;
    border: none;
    
    &.primary {
      background: #1890ff;
      color: white;
    }
    
    &.secondary {
      background: #52c41a;
      color: white;
    }
    
    &.danger {
      background: #ff4d4f;
      color: white;
    }
    
    &.info {
      background: #722ed1;
      color: white;
    }
  }
}

.log-container {
  height: 400rpx;
  background: white;
  border-radius: 16rpx;
  padding: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  
  .log-item {
    display: flex;
    margin-bottom: 10rpx;
    
    .log-time {
      font-size: 24rpx;
      color: #999;
      margin-right: 20rpx;
      min-width: 120rpx;
    }
    
    .log-message {
      font-size: 26rpx;
      color: #333;
      flex: 1;
    }
  }
}
</style>